package controller
/**
 * 个人信息 业务处理
 *
 * @author hanyun
 */
import (
	"fmt"
	"github.com/gin-gonic/gin"
	"hanyun-admin/src/entity"
	"hanyun-admin/src/service"
	"hanyun-admin/src/utils"
	"net/http"
)

//个人信息
func ProFile(c *gin.Context)  {
	token := c.Request.Header.Get("Authorization")
	user := utils.GetLoginUser(token)
	u := service.SelectUserByUserId(user.UserId)
	//u.CreateDate=u.CreateTime.Format("2006-01-02 15:04:05")
	u.Dept = service.SelectDeptByDeptId(u.DeptId)
	role := service.SelectRolesByUserId(user.UserId)
	post := service.SelectPostsByUserId(user.UserId)
	c.JSON(200,gin.H{
		"code":200,
		"data":u,
		"msg":"操作成功",
		"postGroup":post.PostName,
		"roleGroup":role.RoleName,
	})
}
//修改用户信息
func GetUpdateLoginUserInfo(c *gin.Context)  {
	var user entity.User
	c.BindJSON(&user)
	fmt.Println(user.UserId)
	err := service.UpdateUserData(user)
	if err != nil {
		c.JSON(500,gin.H{
			"code":"500",
			"msg":"操作失败！",
		})
		return
	}
	c.JSON(200,gin.H{
		"code":200,
		"msg":"操作成功！",
	})
}
//修改密码
func GetUpdateLoginPassword(c *gin.Context)  {
	//因为前端使用axios传参 使用的发送数据格式用的 query string parameters
	//所以我们用gin提供的方法来接收数据 Query()方法
	oldPassword := c.Query("oldPassword")
	newPassword := c.Query("newPassword")
	//获取token
	token := c.Request.Header.Get("Authorization")
	user := utils.GetLoginUser(token)
	u := service.SelectUserByUserId(user.UserId)
	if oldPassword != u.Password {
		c.JSON(500,gin.H{
			"code":500,
			"msg":"修改密码失败，旧密码错误",
		})
		return
	}
	if oldPassword == newPassword {
		c.JSON(500,gin.H{
			"code":500,
			"msg":"新密码不能与旧密码相同",
		})
		return
	}
	updateUser := entity.User{
		UserId:     u.UserId,
		Password:   newPassword,
	}
	err := service.UpdateUserData(updateUser)
	if err != nil {
		fmt.Println("update user password error ",err)
	}
	c.JSON(200,gin.H{
		"code":200,
		"msg":"修改成功",
	})
}
//修改头像
func GetUpdateAvatar(c *gin.Context)  {
	token := c.Request.Header.Get("Authorization")
	user := utils.GetLoginUser(token)
	file,err := c.FormFile("avatarfile")
	if err != nil {
		c.JSON(http.StatusOK,gin.H{
			"code":http.StatusInternalServerError,
			"msg":"文件错误",
		})
		return
	}
	//开始上传
	fileName, a := utils.FileUpload(file,c)
	if a != nil {
		c.JSON(http.StatusOK,gin.H{
			"code":http.StatusInternalServerError,
			"msg":"文件上传失败！",
		})
		return
	}
	u := entity.User{UserId:user.UserId,Avatar:fileName}
	err = service.UpdateUserData(u)
	if err != nil {
		c.JSON(http.StatusOK,gin.H{
			"code":http.StatusInternalServerError,
			"msg":"文件上传失败！",
		})
		return
	}
	c.JSON(http.StatusOK,gin.H{
		"code":http.StatusOK,
		"imgUrl":fileName,
		"msg":"操作成功！",
	})
}